package com.vcredit.creditcat.framework.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.vcredit.creditcat.service.UserService;

/**
 * 登录过滤
 *
 */
public class LoginFilter extends UsernamePasswordAuthenticationFilter{
	@Autowired
	private UserService userService;
	@Override
	public Authentication attemptAuthentication(HttpServletRequest request,
			HttpServletResponse response) throws AuthenticationException {
		
		String userName = obtainUsername(request);
		String password = obtainPassword(request);
//		String validate = request.getParameter("j_validate");
//		Object imgVal = request.getSession().getAttribute("imageVal");
//		if (imgVal == null || validate == null)
//			throw new AuthenticationServiceException("验证码为空");
//		if (!((String) imgVal).toLowerCase().equals(validate.toLowerCase()))
//			throw new AuthenticationServiceException("验证码不正确");
		if (userService.login(userName, password)) {
			UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(userName,
					password);
			setDetails(request, authRequest);
			return this.getAuthenticationManager().authenticate(authRequest);
		}
		throw new AuthenticationServiceException("用户名或密码错误!");
	}
}
